import React, { useEffect } from "react";
import Web3 from "web3";
import tokenjson from "../build/EalenToken.json"
import exchangejson from "../build/Exchange.json"
import Balance from "./Balance";
import Order from "./Order";
import { loadBalanceData } from "../redux/slices/balanceSlice";
import { useDispatch } from "react-redux";
import { loadAllOrderData, loadCancelOrderData, loadFillOrderData } from "../redux/slices/orderSlice";
export default function Content() {
    const dispatch = useDispatch();
    useEffect(() => {
        async function start() {
            // 1、获取连接后的合约
            const web = await initWeb();

            // 全局对象挂载
            window.web = web;

            // 2、获取资产信息
            dispatch(loadBalanceData(web));

            // 3、获取订单信息
            dispatch(loadCancelOrderData(web));
            dispatch(loadAllOrderData(web));
            dispatch(loadFillOrderData(web));

            // 监听
            web.exchange.events.CancelOrder({
                fromBlock: 0,
                toBlock: 'latest',
            }, () => {
                dispatch(loadCancelOrderData(web));
            })
            web.exchange.events.Order({
                fromBlock: 0,
                toBlock: 'latest',
            }, () => {
                dispatch(loadAllOrderData(web));
            })
            web.exchange.events.Trade({
                fromBlock: 0,
                toBlock: 'latest',
            }, () => {
                dispatch(loadFillOrderData(web));
                dispatch(loadBalanceData(web));
            })
        }
        start();
    }, [dispatch]);

    async function initWeb() {
        const web3 = new Web3(Web3.givenProvider || "http://localhost:8545");

        // 授权
        let accounts = await web3.eth.requestAccounts();

        const networkId = await web3.eth.net.getId();

        const { abi: tokenAbi, networks: tokenNetworks } = tokenjson;
        const { abi: exchangeAbi, networks: exchangeNetworks } = exchangejson;

        const token = await new web3.eth.Contract(tokenAbi, tokenNetworks[networkId].address);
        const exchange = await new web3.eth.Contract(exchangeAbi, exchangeNetworks[networkId].address);

        return {
            web3,
            account: accounts[0],
            token,
            exchange
        };
    }

    return (
        <div className="App" style={{ padding: "10px" }}>
            <Balance></Balance>
            <Order></Order>
        </div>
    );
}